#coding:utf-8

import json,datetime
from MHttpApi import  db, ApiCase,ApiParam,Project,MoudleApi,ApiResult,ApiPlan
from sqlalchemy import not_, and_, or_
import UserManage.userBussiness

def moudle_select_all(project_id,moudle_type):
    query = db.session().query(MoudleApi)
    if project_id != "":

        query = query.filter(MoudleApi.project_id == project_id)
    if moudle_type != "":
        query = query.filter(MoudleApi.moudle_type == moudle_type)
    list = []
    for d in query.all():
        c = d.__dict__
        del (c['_sa_instance_state'])
        list.append(c)
    return list

def project_select_all():
    query = db.session().query(Project)
    query = query.order_by(Project.id.desc())
    list = []
    for d in query.all():
        c = d.__dict__
        del (c['_sa_instance_state'])
        list.append(c)
    return list

def project_select_all_byUserId(openId,token):
    project_id_list  = UserManage.userBussiness.getUserId(openId,token,t=1)
    return project_srh_name(project_id_list,t=1)

def project_srh_name(idList,t=0):
    data = Project.query.filter(Project.id.in_(idList)).all()
    list = []
    for d in data:
        if t == 0:
            list.append(d.project_name)
        else:
            list.append({"project_name":d.project_name,"id":d.id})
    return list


def moudle_srh(project_id,moudle_type,page,limit):
    query = db.session().query(MoudleApi)
    if project_id != "":
        query = query.filter(MoudleApi.project_id == project_id)
    if moudle_type!= "":
        query = query.filter(MoudleApi.moudle_type == moudle_type)
    count = query.count()
    data = query.paginate(int(page), int(limit), False)
    list = []
    for d in data.items:
        c = d.__dict__
        del (c['_sa_instance_state'])
        list.append(c)
    return list,count

def moudle_manage(content):

    if content.has_key("id"):
        if content['id'] != "":
            query = MoudleApi.query.filter(MoudleApi.id == content['id']).first()
            if query:

                query.project_id = content['project_id']

                query.moudle_name = content['moudle_name']
                query.moudle_type = content['moudle_type']
                query.last_time = str(datetime.datetime.now())
                db.session.commit()
                return query.id
    query = MoudleApi.query.filter(and_(MoudleApi.moudle_name == content['moudle_name'],
                                                    MoudleApi.moudle_type == content['moudle_type'])).first()
    if query:
        return False
    MoudleApi(project_id=content['project_id'],moudle_name=content['moudle_name'],moudle_type=content['moudle_type']).add()
    return 1


def project_all(page,limit):
    query = db.session().query(Project)
    query = query.order_by(Project.id.desc())
    count = query.count()
    data = query.paginate(int(page), int(limit), False)
    list = []
    for d in data.items:
        c = d.__dict__
        del (c['_sa_instance_state'])
        list.append(c)
    return list,count

def project_manage(content):

    if content.has_key("id"):
        if content['id'] != "":
            query = Project.query.filter(Project.id == content['id']).first()
            if query:
                query.project_name = content['project_name']
                query.last_time =str(datetime.datetime.now())
                db.session.commit()
                return query.id

    query = Project.query.filter(Project.project_name == content['project_name']).first()
    if query:
        return False
    id = Project(project_name=content['project_name']).add()
    return id

def case_api_plan_all(project_id='',module_id=''):
    query = db.session().query(ApiPlan)
    if project_id != "":
        query = query.filter(ApiPlan.project_id == project_id)
    if module_id != "":
        query = query.filter(ApiPlan.module_id == module_id)
    query = query.filter(and_(ApiPlan.isrun == 0),ApiPlan.id!=1)
    list = []
    for d in query.all():
        c = d.__dict__
        del (c['_sa_instance_state'])
        list.append(c)
    return list

def case_api_plan_srh(project_id,module_id,api_plan_name,page,limit):
    query = db.session().query(ApiPlan)
    if project_id != "":
        query = query.filter(ApiPlan.project_id == project_id)
    if module_id != "":
        query = query.filter(ApiPlan.module_id == module_id)

    if api_plan_name != "":
        path = "%%%s%%" % api_plan_name
        query = query.filter(ApiPlan.api_plan_name.like(path))

    query = query.order_by(ApiPlan.id.desc())
    count = query.count()
    data = query.paginate(int(page), int(limit), False)
    list = []
    for d in data.items:
        c = d.__dict__
        del (c['_sa_instance_state'])


        list.append(c)
    return list, count

def case_api_plan_del(id,isrun = 0):
    query = ApiPlan.query.filter(ApiPlan.id == id).first()
    if query:
        id = query.id
        query.isrun = isrun
        db.session.commit()
        return id
    return False

def case_api_plan_manage(content):
    if content.has_key("id"):
        if content['id'] != "":
            query = ApiPlan.query.filter(ApiPlan.id == content['id']).first()
            if query:
                query.project_id = content['project_id']
                query.module_id = content['module_id']
                query.api_plan_name = content['api_plan_name']
                query.auto_order = content['auto_order']
                if content.has_key("caseIdList"):
                    query.caseIdList = content['caseIdList']
                query.last_time = str(datetime.datetime.now())
                db.session.commit()
                return query.id
    if content.has_key("caseIdList"):
        caseIdList = content['caseIdList']
    else:
        caseIdList = ""
    id = ApiPlan(content['project_id'],content['module_id'],content['api_plan_name'],
                 content['auto_order'],caseIdList=caseIdList).add()
    return id

def case_api_params_srhByName(project_id,param_name):
    """根据参数名称查询出该参数的内容"""
    query = ApiParam.query.filter(and_(ApiParam.param_name == param_name,ApiParam.project_id == project_id)).first()
    if query:
        c = query.__dict__
        del (c['_sa_instance_state'])
        return c
    return False

def case_api_params_srhByCaseId(project_id,case_id):
    """根据参数名称查询出该参数的内容"""
    query = ApiParam.query.filter(and_(ApiParam.case_id == case_id,ApiParam.project_id == project_id)).all()
    if query:
        list = []
        for d in query:
            c = d.__dict__
            del(c['_sa_instance_state'])
            list.append(c)
        return list
    return False

def case_api_params_upparam_value(id,param_value):
    query = ApiParam.query.filter(ApiParam.id == id).first()
    if query:
        id = query.id
        query.param_value = param_value
        db.session.commit()
        return id
def case_api_params_del(id):
    query = ApiParam.query.filter(ApiParam.id == id).first()
    if query:
        id = query.id
        db.session.delete(query)
        db.session.commit()
        return id
    return False

def case_api_params_srh(project_id,param_name,page,limit):
    query = db.session().query(ApiParam)
    if project_id != "":
        query = query.filter(ApiParam.project_id == project_id)
    if param_name != "":
        query = query.filter(ApiParam.param_name == param_name)
    query = query.order_by(ApiParam.id.desc())
    count = query.count()
    data = query.paginate(int(page), int(limit), False)
    list = []
    for d in data.items:
        c = d.__dict__
        del (c['_sa_instance_state'])
        list.append(c)
    return list,count
def case_api_params_manage(content):

    if content.has_key("id"):
        if content['id'] != "":
            query = ApiParam.query.filter(ApiParam.id == content['id']).first()
            if query:
                query.project_id = content['project_id']
                query.param_type = content['param_type']
                query.param_name = "$%s$"%content['param_name']
                query.param_value = content['param_value']
                query.case_id = content['case_id']
                query.leftStr = content['leftStr']
                query.rightStr = content['rightStr']
                query.indexStr = content['indexStr']
                query.jsonObj = content['jsonObj']
                db.session.commit()
                return query.id

    query = ApiParam.query.filter(ApiParam.param_name == "$%s$" % content['param_name']).first()
    if query:
        return False
    id = ApiParam(project_id=content['project_id'],
                  param_type=content['param_type'],
                  param_name = content['param_name'],
                  param_value=content['param_value'],
                  case_id=content['case_id'],
                  leftStr = content['leftStr'],
                  rightStr=content['rightStr'],
                  indexStr=content['indexStr'],
                  jsonObj=content['jsonObj']).add()
    return id


def case_api_by_case_Id(project_id,case_id):
    query = ApiCase.query.filter(and_(ApiCase.project_id == project_id,ApiCase.case_id==case_id)).first()
    if query:
        c = query.__dict__
        del (c['_sa_instance_state'])
        return c
    return False

def case_api_byId(id):
    query = ApiCase.query.filter(ApiCase.id == id).first()
    if query:
        c = query.__dict__
        del (c['_sa_instance_state'])
        return c
    return False

def case_api_all(project_id,module_id):
    query = db.session().query(ApiCase)
    if project_id != "":
        query = query.filter(ApiCase.project_id == project_id)
    if module_id != "":
        query = query.filter(ApiCase.module_id == module_id)
    query = query.filter(ApiCase.is_show == 0)
    query = query.order_by(ApiCase.id.desc())
    list = []
    for d in query.all():
        c = d.__dict__
        list.append(c.get('id'))
    return list


def case_api_srh(project_id,module_id,effect,path,page,limit):
    query = db.session().query(ApiCase)
    if project_id!="":
        query = query.filter(ApiCase.project_id == project_id)
    if module_id!="":
        query = query.filter(ApiCase.module_id == module_id)
    if effect!="":
        effect = "%%%s%%" % effect
        query = query.filter(ApiCase.effect.like(effect))
    if path != "":
        path = "%%%s%%" % path
        query = query.filter(ApiCase.path.like(path))
    query = query.filter(ApiCase.is_show == 0)
    query = query.order_by(ApiCase.id.desc())
    count = query.count()
    data = query.paginate(int(page), int(limit), False)
    list = []
    for d in data.items:
        c = d.__dict__
        up_person = c['person']
        up_person = UserManage.userBussiness.getNameById(up_person)
        c['person_name'] = up_person
        del(c['_sa_instance_state'])
        list.append(c)
    return list,count


def case_api_del(id):
    """将case删除不再显示出来"""
    query = ApiCase.query.filter(ApiCase.id == id).first()
    if query:
        query.is_show = 1
        db.session.commit()
    return query.id

def is_json(myjson):
    try:
        return json.loads(myjson)
    except ValueError:
        return False

def case_api_manage(content):
    """管理测试用例"""
    h = is_json(content['headersJson'])
    if h != False:
        headersJson = json.dumps(h)
    else:
        headersJson = content['headersJson']

    b = is_json(content['bodysJson'])
    if b != False:
        bodysJson = json.dumps(b)
    else:
        bodysJson = content['bodysJson']
    chkSon = content['chkJson']
    chkJson = json.dumps([c for c in chkSon if c!=[] and c.get('chkStr')!=''])
    if content.has_key("id"):
        if content['id']!="":
            query = ApiCase.query.filter(ApiCase.id == content['id']).first()
            if query:
                query.project_id = content['project_id']
                query.module_id = content['module_id']
                query.effect = content['effect']
                query.method = content['method']
                query.req_type = content['req_type']
                query.host = content['host']
                query.path = content['path']
                query.pre_caseId = content['pre_caseId']
                query.run_times = content['run_times']
                query.concurrent = content['concurrent']
                query.headersJson = headersJson
                query.bodysJson = bodysJson
                query.chkJson = chkJson
                query.person = content['person']
                db.session.commit()
                return {"id":query.id,"caseId":query.case_id}
    id = ApiCase(project_id = content['project_id'],
                        module_id = content['module_id'],
                        effect= content['effect'] ,
                        method= content['method'],
                        req_type= content['req_type'],
                        host= content['host'],
                        path= content['path'],
                        pre_caseId= content['pre_caseId'],
                        run_times= content['run_times'],
                        concurrent= content['concurrent'],
                        headersJson= headersJson,
                        bodysJson= bodysJson,
                        chkJson= chkJson,
                        person= content['person']).add()
    return id

def case_api_result(project_id,module_id,api_plan_id,api_result,case_id,responseJson,responseJsonTime,path):
    """插入测试结果"""
    ApiResult(project_id,module_id,api_plan_id,api_result,case_id,responseJson,responseJsonTime,path).add()


def case_result_rspTime(path):
    query = db.session().query(ApiResult)
    query = query.filter(ApiResult.path.like(path))
    query = query.order_by(ApiResult.id.desc())
    timelist = []
    dataList = []
    for d in query.all():
        timelist.append(d.responseJsonTime)
        dataList.append(d.last_time)
    return timelist,dataList


def case_api_result_srh(project_id,module_id,api_plan_id,api_result,path,page,limit):
    query = db.session().query(ApiResult)
    if project_id != "":
        query = query.filter(ApiResult.project_id == project_id)
    if module_id != "":
        query = query.filter(ApiResult.module_id == module_id)
    if api_plan_id != "":
        query = query.filter(ApiResult.api_plan_id == api_plan_id)
    if api_result != "":
        query = query.filter(ApiResult.api_result == api_result)
    if path != "":
        path = "%%%s%%" % path
        query = query.filter(ApiResult.path.like(path))
    query = query.order_by(ApiResult.id.desc())
    count = query.count()
    data = query.paginate(int(page), int(limit), False)
    list = []
    for d in data.items:
        c = d.__dict__
        del (c['_sa_instance_state'])
        c['responseJson']=json.loads(c['responseJson'])
        list.append(c)
    return list, count